package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.article.feign.BehaviorFeign;
import com.usian.article.mapper.ApCollectionMapper;
import com.usian.article.service.ApCollectionService;
import com.usian.model.article.dtos.CollectionBehaviorDto;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.threadlocal.UserIdThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionServiceImpl extends BaseServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult isCollection(CollectionBehaviorDto dto) {
        //1.参数校验
        if (dto == null || dto.getEntryId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询行为实体
        Integer userId = UserIdThreadLocalUtils.getUserId();
        if (userId == null)return needLogin;

        if (dto.getPublishedTime() == null)dto.setPublishedTime(new Date());

        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getEntryId, apBehaviorEntry.getId()).
                eq(ApCollection::getArticleId, dto.getEntryId()));
        if (dto.getOperation() == 0) {
            //3.保存收藏行为
            if (apCollection == null) {
                apCollection = new ApCollection();
                apCollection.setArticleId(dto.getEntryId());
                apCollection.setEntryId(apBehaviorEntry.getId());
                apCollection.setType(dto.getType());
                apCollection.setCollectionTime(new Date());
                apCollection.setPublishedTime(dto.getPublishedTime());
                save(apCollection);
            } else {
                return ResponseResult.errorResult("该文章已收藏");
            }
        }else {
            if (apCollection != null && apCollection.getId()!=null){
                removeById(apCollection.getId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
